<?php

namespace app\admin\model;

use think\Model;

class UserPoints extends Model
{
    // 表名
    protected $name = 'user_points';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
        'source_text'
    ];

    // 积分来源列表
    public static $sourceList = [
        'daily_question' => '每日答题',
        'sign_in' => '签到',
        'task_complete' => '任务完成',
        'admin_reward' => '管理员奖励',
        'admin_deduct' => '管理员扣除'
    ];

    public function getSourceList()
    {
        return self::$sourceList;
    }

    public function getSourceTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source']) ? $data['source'] : '');
        $list = $this->getSourceList();
        return isset($list[$value]) ? $list[$value] : $value;
    }

    /**
     * 添加积分记录
     * @param int $userId 用户ID
     * @param int $points 积分数量
     * @param string $source 积分来源
     * @param int $sourceId 来源关联ID
     * @param string $description 描述
     * @return int added_points int 添加的积分数
     * @return int today_points int 今日积分数
     */
    public static function addPoints($userId, $points, $source = 'daily_question', $sourceId = 0, $description = '', $classes_id = 0, $type = 2, $remarks = '')
    {
        $data = [
            'user_id' => $userId,
            'points' => $points,
            'source' => $source,
            'source_id' => $sourceId,
            'description' => $description,
            'date' => date('Y-m-d'),
            'create_time' => time(),
            'update_time' => time(),
            'status' => 1
        ];

        $model = new self();
        $result = $model->save($data);
        
        if ($result) {
            // 更新用户积分汇总
            self::updateUserPointsSummary($userId);
        }
        $today_points = self::where([
            'user_id' => $userId,
            'date' => date('Y-m-d'),
            'status' => 1
        ])->sum('points');
        
        // 计算总积分
        $totalPoints = self::where([
            'user_id' => $userId,
            'status' => 1
        ])->sum('points');

        // 今日该类型次数
        $todayCount = self::where([
            'user_id' => $userId,
            'source' => $source,
            'date' => date('Y-m-d'),
            'status' => 1
        ])->count();
        
        return array($today_points??0,$points??0,$totalPoints??0,$todayCount??0);
    }

    /**
     * 检查用户今日是否已获得指定来源的积分
     * @param int $userId 用户ID
     * @param string $source 积分来源
     * @return bool
     */
    public static function checkTodayPoints($userId, $source = 'daily_question')
    {
        $model = new self();
        $count = $model->where([
            'user_id' => $userId,
            'source' => $source,
            'date' => date('Y-m-d'),
            'status' => 1
        ])->count();
        
        return $count > 0;
    }

    /**
     * 获取用户积分记录
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public static function getUserPoints($userId, $page = 1, $limit = 20)
    {
        $model = new self();
        $list = $model->where([
            'user_id' => $userId,
            'status' => 1
        ])
        ->order('create_time desc')
        ->page($page, $limit)
        ->select();

        $total = $model->where([
            'user_id' => $userId,
            'status' => 1
        ])->count();

        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 更新用户积分汇总
     * @param int $userId 用户ID
     */
    public static function updateUserPointsSummary($userId)
    {
        $model = new self();
        
        // 计算总积分
        $totalPoints = $model->where([
            'user_id' => $userId,
            'status' => 1
        ])->sum('points');

        // 计算今日积分
        $todayPoints = $model->where([
            'user_id' => $userId,
            'date' => date('Y-m-d'),
            'status' => 1
        ])->sum('points');

        // 更新或创建汇总记录
        $summaryModel = new UserPointsSummary();
        $summary = $summaryModel->where('user_id', $userId)->find();
        
        if ($summary) {
            $summary->total_points = $totalPoints;
            $summary->available_points = $totalPoints; // 暂时设为总积分，后续可扩展消费功能
            $summary->today_points = $todayPoints;
            $summary->update_time = time();
            $summary->save();
        } else {
            $summaryModel->save([
                'user_id' => $userId,
                'total_points' => $totalPoints,
                'available_points' => $totalPoints,
                'used_points' => 0,
                'today_points' => $todayPoints,
                'create_time' => time(),
                'update_time' => time(),
                'status' => 1
            ]);
        }
    }

    /**
     * 获取用户积分汇总
     * @param int $userId 用户ID
     * @return array
     */
    public static function getUserPointsSummary($userId)
    {
        $summaryModel = new UserPointsSummary();
        $summary = $summaryModel->where('user_id', $userId)->find();

        if (!$summary) {
            // 如果没有汇总记录，创建一个
            self::updateUserPointsSummary($userId);
            $summary = $summaryModel->where('user_id', $userId)->find();
        }
        
        return $summary ? $summary->toArray() : [
            'user_id' => $userId,
            'total_points' => 0,
            'available_points' => 0,
            'used_points' => 0,
            'today_points' => 0
        ];
    }

    public function getPoints($userId,$source){
        $today_points = self::where([
            'user_id' => $userId,
            'date' => date('Y-m-d'),
            'status' => 1
        ])->sum('points');
        
        // 计算总积分
        $totalPoints = self::where([
            'user_id' => $userId,
            'status' => 1
        ])->sum('points');

        // 今日该类型次数
        $todayCount = self::where([
            'user_id' => $userId,
            'source' => $source,
            'date' => date('Y-m-d'),
            'status' => 1
        ])->count();

        return array($today_points??0,$totalPoints??0,$todayCount??0);
    }
}